from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import os
import sys

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(__file__))

from config import settings
from database import create_tables
from routes import auth, chat

# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    description="多模态AI聊天应用后端API",
    version="1.0.0",
    debug=settings.debug
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.get_allowed_origins(),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件目录
if os.path.exists("uploads"):
    app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

# 确保上传目录存在
if not os.path.exists("uploads"):
    os.makedirs("uploads")
if not os.path.exists("uploads/images"):
    os.makedirs("uploads/images")
if not os.path.exists("uploads/files"):
    os.makedirs("uploads/files")

# 包含路由
app.include_router(auth.router)
app.include_router(chat.router)


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    # 创建数据库表
    create_tables()
    
    # 创建上传目录
    if not os.path.exists("uploads"):
        os.makedirs("uploads")
    
    print(f"{settings.app_name} 后端服务已启动")


@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.app_name}",
        "version": "1.0.0",
        "status": "运行中"
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy"}





if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.debug,
        log_level="info"
    )